import React, { useEffect, useState } from 'react'
import { Form, Input, Button, Space } from 'antd';
import { addUser, editUser } from '../../api/user'
import Message from '../../components/Message';
import AppDialog from '../../components/AppDialog'

const AddOrEditUser = ({ visible, userInfo, onHide }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (visible && userInfo.id) {
      const initialValues = {
        username: userInfo.username,
        email: userInfo.email,
        mobile: userInfo.mobile
      }
      form.setFieldsValue(initialValues)
    }
  }, [userInfo])

  // 点击确定
  const onFinish = async (values) => {
    setLoading(true)
    if (!userInfo.id) {
      await addUser(values).finally(() => {
        setLoading(false)
      })
      Message("success", "添加用户成功");
    } else {
      values.id = userInfo.id
      await editUser(values).finally(() => {
        setLoading(false)
      })
      Message("success", "编辑用户成功");
    }
   
    handleDialogClosed('success')
  };

  // 提交表单且数据验证失败后回调事件
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 点击取消
  const handleDialogClosed = (type) => {
    form.resetFields();
    onHide(type)
  };

  // 验证邮箱规则
  const checkEmail = (rule, value, callback) => {
    if (!value) callback();
    let reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    if (reg.test(value)) {
      callback();
    } else {
      callback(new Error("请输入正确的邮箱"));
    }
  };

  // 验证手机号规则
  const checkMobile = (rule, value, callback) => {
    if (!value) callback();
    let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
    if (reg.test(value)) {
      callback();
    } else {
      callback(new Error("请输入正确的手机号码"));
    }
  };

  const tailLayout = {
    wrapperCol: {
      offset: 10,
      span: 14,
    },
  };

  return (visible ?
    <AppDialog
      title={userInfo.id ? '编辑用户信息' : '添加用户'}
      visible={visible}
      onClosed={handleDialogClosed}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            { required: true, message: '请输入用户名' },
            { min: 3, max: 10, message: "长度在 3 到 10 个字符" }
          ]}
        >
          <Input disabled={userInfo.id ? true : false} />
        </Form.Item>
        {
          !userInfo.id &&
          <Form.Item
          label="密码"
          name="password"
          rules={[
            { required: true, message: '请输入密码' },
            { min: 6, max: 15, message: "长度在 6 到 15 个字符" }
          ]}
        >
          <Input.Password />
        </Form.Item>
        }
       
        <Form.Item
          label="邮箱"
          name="email"
          rules={[
            { required: true, message: '请输入邮箱' },
            { validator: checkEmail, trigger: "blur" }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="手机号"
          name="mobile"
          rules={[
            { required: true, message: '请输入手机号' },
            { validator: checkMobile, trigger: "blur" }
          ]}
        >
          <Input maxLength={11}/>
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              确定
            </Button>
            <Button onClick={() => handleDialogClosed()}>
              取消
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </AppDialog>
    : null
  )
}

export default AddOrEditUser